﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace fasc_openapi_donet_sdk.Common
{
    public class SignUtil
    {
        /// <summary>
        /// 根据参数获取签名值
        /// </summary>
        /// <returns></returns>
        public static string GetSignByParams(IEnumerable<KeyValuePair<string, string>> dic, string timeStamp,string appSecret)
        {
            string sign = null;
            string signContent = SortParamsForSign(dic);
            string signText = CryptoProvider.sha256(signContent).ToLower();
            byte[] secretSign = CryptoProvider.HMACSHA256Byte(timeStamp, appSecret);
            sign = CryptoProvider.HMACSHA256Str(signText.ToLower(), secretSign);
            return sign;
        }


        /// <summary>
        /// 按照参数键值ASCII码递增排序
        /// </summary>
        /// <param name="dic"></param>
        /// <returns></returns>
        public static string SortParamsForSign(IEnumerable<KeyValuePair<string, string>> dic)
        {
            dic = dic.Where(r => string.IsNullOrEmpty(r.Value) == false).OrderBy(x => x.Key, new OrdinalComparer()).ToDictionary(x => x.Key, y => y.Value);

            var content = string.Join("&", dic.Select(r => r.Key + "=" + r.Value));

            return content;
        }
    }
}
